/**
 * 漆水河 脚手架基础公开课
 * 2022/8/13 --- 2022/12/13
 * 有疑问可加QQ群: 809126489，后续会持续输出与大家一起成长
 */
package com.qishuihe.basedomain.infrastructure.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.qishuihe.basedomain.infrastructure.vo.LoginUserVO;
import com.qishuihe.basedomain.infrastructure.uuid.SnowFlake;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class InitBaseEntityHandler implements MetaObjectHandler {

    @Autowired
    private SnowFlake snowFlake;
    @Override
    public void insertFill(MetaObject metaObject) {
        long id = snowFlake.nextId();
        this.fillStrategy(metaObject,"id",id);
        Authentication authentication =SecurityContextHolder.getContext().getAuthentication();
        if(null!=authentication) {
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
            LoginUserVO loginUserDTO = (LoginUserVO) usernamePasswordAuthenticationToken.getPrincipal();
            this.fillStrategy(metaObject, "createBy", loginUserDTO.getUsername());
        }
        this.fillStrategy(metaObject,"createDate",new Date());

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUserVO loginUserDTO =(LoginUserVO)usernamePasswordAuthenticationToken.getPrincipal();
        this.fillStrategy(metaObject,"updateBy", loginUserDTO.getUsername());
        this.fillStrategy(metaObject,"updateDate",new Date());
    }
}
